﻿/*
 * Copyright 2008 Lucifer Lu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Json;
using SilverChart.Core.Configuration;
using SilverChart.Core.Service;
using System.Reflection;
using System.Collections.Generic;

namespace SilverChart.JsonConfiguration {
    [ServiceProvider(LayzeCreation = true, Singleton = false, ServiceName = JsonConfigurationParserFactory.FACTORY_NAME)]
    public class JsonConfigurationParserFactory : ConfigurationParserFactory {
        //Logger logger = Logger.GetLogger<JsonConfigurationParserFactory>();
        public const String FACTORY_NAME = "Json Configuration Factory";

        #region ConfigurationFactory Members

        public bool IsCompatible(String ConfigString) {
            try {
                JsonValue.Parse(ConfigString);
                //logger.Debug(ConfigString + "is JSON String");
                return true;
            }
            catch {
                //logger.Debug(ConfigString + "is not JSON String");
                return false;
            }
        }

        public ConfigurationParser CreateParser(string ConfigString, string RootItemName) {
            JsonValue value = JsonValue.Parse(ConfigString);
            if (value.JsonType != JsonType.Object) {
                throw new ArgumentException("Configuration must be a JSon Object");
            }
            JsonConfigurationParser parser = new JsonConfigurationParser((JsonObject)value);

            IList<Type> rootTypes = ServiceManager.Instance.GetService<ConfigurationService>().GetRootConfiguratioItems(RootItemName);
            if (rootTypes.Count == 0) {
                return null;
            }
            Type rootType = rootTypes[0];

            ConfigurationItem configItem = AbstractConfigurationItem.CreateInstance(rootType, parser);

            if (configItem != null) {
                parser.Configuration = configItem;
            }
            else {
                throw new ArgumentException("Can not create instance of type " + rootType.FullName);
            }
            return parser;
        }

        #endregion
    }
}
